package com.blog.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blog.entity.Category;
import com.blog.service.CategoryService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/categories")
@CrossOrigin
public class CategoryController {

    private final CategoryService categoryService;

    public CategoryController(CategoryService categoryService) {
        this.categoryService = categoryService;
    }

    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> createCategory(@RequestBody Category category) {
        return ResponseEntity.ok(categoryService.createCategory(category));
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> updateCategory(@PathVariable Long id, @RequestBody Category category) {
        category.setId(id);
        return ResponseEntity.ok(categoryService.updateCategory(category));
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> deleteCategory(@PathVariable Long id) {
        // 检查分类下是否有文章
        if (categoryService.hasArticles(id)) {
            Map<String, Object> response = new HashMap<>();
            response.put("message", "该分类下有文章，无法删除");
            response.put("hasArticles", true);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
        }
        categoryService.deleteCategory(id);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getCategory(@PathVariable Long id) {
        return ResponseEntity.ok(categoryService.findById(id));
    }

    @GetMapping
    public ResponseEntity<?> getAllCategories(
            @RequestParam(required = false) Integer current,
            @RequestParam(required = false) Integer size) {
        if (current != null && size != null) {
            Page<Category> page = new Page<>(current, size);
            IPage<Category> categories = categoryService.findAll(page);
            return ResponseEntity.ok(categories);
        } else {
            List<Category> categories = categoryService.findAll();
            return ResponseEntity.ok(categories);
        }
    }
} 